package pers.chy.chyappointmentplatform.Controller;


import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.chy.chyappointmentplatform.Model.NoMapping.ReplyMsgDTO;
import pers.chy.chyappointmentplatform.Model.NoMapping.UserDTO;
import pers.chy.chyappointmentplatform.Service.LoginService;
import pers.chy.chyappointmentplatform.Utils.ChyException;
import pers.chy.chyappointmentplatform.Utils.JwtUtil;

import java.util.Map;

@RestController
@CrossOrigin        // 允许跨域请求
@RequestMapping("LoginController")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("login")
    public String login(@RequestBody Map params) {
        ReplyMsgDTO replyMsgDTO = new ReplyMsgDTO();

        // 日志
        Logger log = LoggerFactory.getLogger(LoginController.class); // 使用指定的类XXX初始化日志对象，方便在日志输出的时候，可以打印出日志信息所属的类。
        log.info("[Controller入参]：" + params);

        try {

            // 获取用户信息
            UserDTO userDTO = loginService.doLogin(params.get("userName").toString(), params.get("password").toString(), Long.parseLong(params.get("roleID").toString()));
            log.info(String.format("用户登录成功：%s-%s-%s", userDTO.getYgdm(), userDTO.getYgxm(), userDTO.getKsmc()));

            // 生成token令牌
            String token = JwtUtil.createToken(userDTO);

            // 业务成功
            replyMsgDTO.setStatus(true);
            replyMsgDTO.setDetail(token);

        } catch (Exception ex) {
            // 业务失败
            replyMsgDTO.setStatus(false);
            replyMsgDTO.setDetail(ex.getMessage());
            // 异常日志
            if (ex instanceof ChyException) log.error("[错误]" + ex.getMessage());
            else log.error("[不期望的异常]", ex);
        }


        //
        String replyMsgStr = new Gson().toJson(replyMsgDTO);
        log.info("[Controller出参]：" + replyMsgStr);
        return replyMsgStr;
    }
}
